# -*- coding: utf-8 -*-
# time: 2025/5/9 16:11
# file: mcp01.py
# author: hanson

"""
# pip install fastapi-mcp
pip install fastmcp
https://blog.csdn.net/lingding_cn/article/details/147355620
FastMCP简介
FastMCP是一个基于Python的高级框架，专为构建MCP服务器而设计。它极大简化了MCP服务器的开发流程，让开发者能够以最小的代码量创建功能强大的MCP服务器。

FastMCP的主要特点包括：

简洁的API：通过装饰器模式，简化MCP服务器的创建
丰富的功能：支持工具（Tools）、资源（Resources）、提示模板（Prompts）等MCP核心元素
多种传输方式：支持stdio和SSE等不同传输协议
类型安全：利用Python的类型提示，自动生成MCP协议所需的模式定义
内置图像处理：支持图像数据的自动格式转换和处理

"""
import random

from fastmcp import FastMCP

# 创建MCP服务器实例
mcp = FastMCP("hanson", port=7200)

# 模拟的天气数据
weather_data = {
    "New York": {"temp": range(10, 25), "conditions": ["sunny", "cloudy", "rainy"]},
    "London": {"temp": range(5, 20), "conditions": ["cloudy", "rainy", "foggy"]},
    "Tokyo": {"temp": range(15, 30), "conditions": ["sunny", "cloudy", "humid"]},
    "Sydney": {"temp": range(20, 35), "conditions": ["sunny", "clear", "hot"]},
}


@mcp.tool()
def add(a: int, b: int) -> int:
    """将两个数字相加"""
    return a + b


@mcp.tool()
def multiply(a: int, b: int) -> int:
    """将两个数相乘"""
    return a * b


@mcp.tool()
def get_weather(city: str) -> dict:
    """获取指定城市的当前天气"""
    if city not in weather_data:
        return {"error": f"无法找到城市 {city} 的天气数据"}

    data = weather_data[city]
    temp = random.choice(list(data["temp"]))
    condition = random.choice(data["conditions"])

    return {
        "city": city,
        "temperature": temp,
        "condition": condition,
        "unit": "celsius"
    }

@mcp.resource("weather://cities")
def get_available_cities() -> list:
    """获取所有可用的城市列表"""
    return list(weather_data.keys())


@mcp.resource("weather://forecast/{city}")
def get_forecast(city: str) -> dict:
    """获取指定城市的天气预报资源"""
    if city not in weather_data:
        return {"error": f"无法找到城市 {city} 的天气预报"}

    forecast = []
    for i in range(5):  # 5天预报
        data = weather_data[city]
        temp = random.choice(list(data["temp"]))
        condition = random.choice(data["conditions"])
        forecast.append({
            "day": i + 1,
            "temperature": temp,
            "condition": condition
        })

    return {
        "city": city,
        "forecast": forecast,
        "unit": "celsius"
    }

if __name__ == "__main__":
    # 使用stdio传输方式启动服务器
    mcp.run(transport="sse")


